package com.quiz.bis.util;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;

/**
 * HTML 工具类
 */
public class HtmlUtils {

    /**
     * 将HTML转换为纯文本，保留基本格式（如换行、段落）
     * @param html HTML内容
     * @return 纯文本
     */
    public static String htmlToText(String html) {
        if (html == null || html.isEmpty()) {
            return "";
        }

        Document document = Jsoup.parse(html);
        FormattingVisitor formatter = new FormattingVisitor();
        NodeTraversor.traverse(formatter, document);

        return formatter.toString().trim();
    }

    /**
     * 自定义格式化访问器
     */
    private static class FormattingVisitor implements NodeVisitor {
        private final StringBuilder accum = new StringBuilder();

        @Override
        public void head(Node node, int depth) {
            if (node instanceof TextNode) {
                TextNode textNode = (TextNode) node;
                String text = textNode.text().trim();
                if (!text.isEmpty()) {
                    accum.append(text);
                }
            } else if (node instanceof Element) {
                Element element = (Element) node;
                String tagName = element.tagName();

                // 处理块级元素
                if (isBlockElement(tagName)) {
                    if (accum.length() > 0 && !endsWithWhitespace(accum)) {
                        accum.append(" ");
                    }
                }

                // 处理特定标签
                switch (tagName) {
                    case "br":
                    case "p":
                    case "div":
                    case "h1":
                    case "h2":
                    case "h3":
                    case "h4":
                    case "h5":
                    case "h6":
                    case "tr":
                        accum.append("\n");
                        break;
                    case "li":
                        accum.append("\n * ");
                        break;
                    case "img":
                        String alt = element.attr("alt");
                        if (!alt.isEmpty()) {
                            accum.append(" [图片: ").append(alt).append("] ");
                        } else {
                            accum.append(" [图片] ");
                        }
                        break;
                }
            }
        }

        @Override
        public void tail(Node node, int depth) {
            if (node instanceof Element) {
                Element element = (Element) node;
                String tagName = element.tagName();

                switch (tagName) {
                    case "p":
                    case "div":
                    case "h1":
                    case "h2":
                    case "h3":
                    case "h4":
                    case "h5":
                    case "h6":
                        accum.append("\n");
                        break;
                    case "td":
                        accum.append("\t");
                        break;
                }
            }
        }

        private boolean isBlockElement(String tagName) {
            return tagName.equals("p") || tagName.equals("div") ||
                    tagName.matches("h[1-6]") || tagName.equals("blockquote") ||
                    tagName.equals("ul") || tagName.equals("ol") ||
                    tagName.equals("pre") || tagName.equals("table");
        }

        private boolean endsWithWhitespace(StringBuilder sb) {
            return sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1));
        }

        @Override
        public String toString() {
            return accum.toString();
        }
    }
}